package com.game.service.app.get_score;

import com.game.service.app.PostJson;
import com.game.service.db.UserScoreDaoImpl;
import com.game.service.socket.FileUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;

import static com.game.service.app.Score.doPostForm;
import static com.game.service.app.Utils.LogDate;
import static com.game.service.define.RoomConfig.*;

public class SaveUserScore {
    private ISendListener mISendListener;

    public void addListener(ISendListener iSendListener) {
        mISendListener = iSendListener;
    }

    public static final String DESC_NORMAL_EXIT = "正常结算";
    public static final String DESC_SYSTEM_EXIT = "系统结算";
    public static final String DESC_UNLOCK = "解锁结算";

    private void add(String pid, String json, String url, String desc) {
        PostJson postJson = new PostJson();
        long time = System.currentTimeMillis();
        postJson.setPid(pid);
        postJson.setGameid(GAME_ID);
        postJson.setPostJson(json);
        postJson.setPostResult(0);
        postJson.setPostUrl(url);
        postJson.setJsonDesc(desc);
        postJson.setAddCurrentTimeMillis(time);
        UserScoreDaoImpl.getInstance().addUserScore(postJson);
    }

    public void saveUserScore(String pid, String json, String url, String desc) {
        PostJson userScore = UserScoreDaoImpl.getInstance().getUserScore(pid);
        if (userScore == null) {//新增
            add(pid, json, url, desc);
        } else {//更新数据
            UserScoreDaoImpl.getInstance().updateUserScore(pid, json, desc);
        }
    }

    private void post(PostJson json, int maxPost) {
        if (json.getPostResult() == 1) {//等于1时表示已经处理成功
            return;
        }
        if (maxPost-- == 0) {
            FileUtils.writeTxtToFile("发送失败,等待下次发送" + json, LogDate(), LOG_NAME_FAIL_JSON);
            return;
        }

        int finalMaxPost = maxPost;
        new Thread(() -> {
            String result = doPostForm(json.getPostUrl(), json.getPostJson());
            String log = "发送结果,第" + (EXIT_MAX_POST - finalMaxPost) + "次,id=" + json.getPid() + "返回=" + result;
            FileUtils.writeTxtToFile(log, LogDate(), LOG_NAME_FAIL_JSON);
            //  {"code":0,"msg":"ok","data":""}
         //   System.out.println("SaveUserScore,"+log);
            if (result.isEmpty()) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                post(json, finalMaxPost);
                return;
            }
            Type type0 = new TypeToken<JsonBean<String>>() {
            }.getType();
            JsonBean<String> bean = new Gson().fromJson(result, type0);
            if (bean != null && bean.code == 0) {
                json.setPostResult(1);//发送成功
                UserScoreDaoImpl.getInstance().userExit(json.getPid(), SaveUserScore.DESC_UNLOCK);//修改为已经处理
                if (mISendListener != null) {
                    mISendListener.sendSuccess();//发送成功
                }
                //  FileUtils.writeTxtToFile("数据发送,发送成功:" + json, LogDate(), LOG_NAME_POST_JSON);

            }

        }).start();
    }

    /**
     * 1.登录时检查玩家是否卡分。
     * 2.如果有卡分则先解锁玩家分数给总服务器,
     * 3. 解锁成功后执行下一步,获取分数。
     * 4. 通过ISendListener接口通知
     *
     * @param pid 玩家id
     */

    public void checkDBUserScore(String pid) {
        new Thread(() -> {
            //检查是否登录过数据库，
            PostJson userScore = UserScoreDaoImpl.getInstance().getUserScore(pid);
            //有则检查是否结算过，等于0表示卡分了，需要提交结算
            if (userScore != null && userScore.getPostResult() == 0) {
                post(userScore, EXIT_MAX_POST);
            } else {
                //直接获取分数
                mISendListener.sendSuccess();
            }
        }).start();
    }

    public interface ISendListener {
        void sendSuccess();

        void sendError();

    }
}
